/*
 * 文件名：topicInfoController.java	 
 * 时     间：下午4:20:10
 * 作     者：liyf       
 * 版     权： 2014-2022  智慧园区, 公司保留所有权利.
 * 联     系：www.szyungu.com
 */
package com.cz073586.technology.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cz073586.common.contants.CommonContans;
import com.cz073586.common.controller.BaseController;
import com.cz073586.common.entity.pojo.PageInfo;
import com.cz073586.technology.model.AdInfo;
import com.cz073586.technology.model.MerchantInfo;
import com.cz073586.technology.model.TopicInfo;
import com.cz073586.technology.model.TopicType;
import com.cz073586.technology.model.UserInfo;
import com.cz073586.technology.service.face.AdInfoService;
import com.cz073586.technology.service.face.TopicInfoService;
import com.cz073586.technology.service.face.TopicTypeService;
import com.cz073586.technology.service.face.UserInfoService;
import com.cz073586.tools.privilege.ResourceAndOperate;
import com.cz073586.tools.util.JsonUtil;
import com.cz073586.tools.util.Tools;
import com.cz073586.tools.util.UUIDGenerateUtil;

/**
 * @ClassName: topicInfoController
 * @Description: 新闻等信息信息
 * @author zengqj
 * @date 2015年1月20日 下午4:20:10
 */
@RestController
@RequestMapping(value = "/topicInfoManager", method = RequestMethod.POST)
@ResourceAndOperate(moduleID = "com.technology.topicInfoManager", moduleName = "新闻管理", resouceDesc = "新闻管理", parentModuleID = "com.technology", parentModuleName = "昱显科技项目")
public class TopicInfoController extends BaseController
{
	@Autowired
	private TopicInfoService topicInfoService;
	
	@Autowired
	private AdInfoService adInfoService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
	private TopicTypeService topicTypeService;
	
	/**
	 * 
	 * @方法名称: queryServicesByPage
	 * @描述: 查询新闻等信息列表
	 *
	 * @参数:
	 * @param page
	 * @return
	 *
	 * @返回类型: ModelMap
	 * @作者:zengqj
	 * @可能抛出异常:
	 */
	@RequestMapping(value = "/queryTopicInfoByPage.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.queryTopicInfoListByPage", 
						moduleName = "查询", 
						resouceDesc = "分页查询新闻信息",
						parentModuleID = "com.technology.topicInfoManager", 
						parentModuleName = "新闻管理")
	public ModelMap queryTopicInfoListByPage(@RequestBody TopicInfo topicInfo)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			PageInfo<TopicInfo> page = topicInfoService
					.queryByObject(topicInfo);
			List<AdInfo> listAdInfo = new ArrayList<AdInfo>();
			if(null!=topicInfo.getType())
			{
				
				TopicType topicType = topicTypeService.selectByPrimaryKey(topicInfo.getType().toString());
				if(null!=topicType&&!Tools.isEmpty(topicType))
				{
					String[] adIds = topicType.getBindToId().split(",");
					for (String adId : adIds)
					{
						AdInfo adInfo = new AdInfo();
						adInfo = adInfoService.selectByPrimaryKey(adId);
						if (null != adInfo)
						{
							listAdInfo.add(adInfo);
						}
					}
				}
			}
			if (CollectionUtils.isNotEmpty(listAdInfo))
			{
				resultMap.put("adInfo", listAdInfo);
			}
			resultMap.put(CommonContans.STRUTS_DATA, page);
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	@RequestMapping(value = "/queryTopicTypeByPage.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.queryTopicTypeByPage", moduleName = "查询", resouceDesc = "分页查询帖子类型的信息", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap queryTopicTypeByPage(@RequestBody TopicType topicType)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			PageInfo<TopicType> page = topicTypeService
					.queryByObject(topicType);
			resultMap.put(CommonContans.STRUTS_DATA, page);
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	/**
	 * 
	 * @方法名称: querytopicInfoById
	 * @描述: 通过新闻等信息ID查询
	 *
	 * @参数:
	 * @param topicInfoId
	 * @return
	 *
	 * @返回类型: ModelMap
	 * @作者:zengqj
	 * @可能抛出异常:
	 */
	@RequestMapping(value = "/queryTopicInfoById.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.queryTopicInfoById", moduleName = "查询单一对象", resouceDesc = "", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap queryTopicInfoById(String topicInfoId)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			
			resultMap.put(CommonContans.STRUTS_DATA,
					topicInfoService.selectByPrimaryKey(topicInfoId));
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	@RequestMapping(value = "/queryTopicTypeById.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.queryTopicTypeById", moduleName = "查询单一对象", resouceDesc = "查询帖子类型对象", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap queryTopicTypeById(String topictypeId)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			TopicType topicType = topicTypeService
					.selectByPrimaryKey(topictypeId);
			List<AdInfo> listAdInfo =  new ArrayList<AdInfo>();
			List<AdInfo> listUnAdInfo =  new ArrayList<AdInfo>();
			if (StringUtils.isNotBlank(topicType.getBindToId()))
			{
				listAdInfo = adInfoService.queryAdByIdsIn(topicType
						.getBindToId().split(","));
				listUnAdInfo = adInfoService
						.queryAdByIdsNotIn(topicType.getBindToId().split(","));
				
			}else
			{
				String[] str = new String[]{""};
				listUnAdInfo = adInfoService
						.queryAdByIdsNotIn(str);
			}
			if (CollectionUtils.isNotEmpty(listAdInfo))
			{
				topicType.setListAdInfo(listAdInfo);
			}
			if (CollectionUtils.isNotEmpty(listUnAdInfo))
			{
				topicType.setListUnAdInfo(listUnAdInfo);
			}
			resultMap.put(CommonContans.STRUTS_DATA, topicType);
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	/**
	 * 
	 * 方法描述：添加新闻等信息，uuid由代码写入
	 * 
	 * @Title: inserttopicInfo
	 * @param @param topicInfo
	 * @param @return
	 * @return ModelMap
	 * @topicInfo topicInfoministrator 2015年1月21日
	 * @throws
	 */
	@RequestMapping(value = "/insertTopicInfo.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.insertTopicInfo", moduleName = "添加", resouceDesc = "", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap insertTopicInfo(@RequestBody TopicInfo topicInfo)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			topicInfo.setUuid(UUIDGenerateUtil.generate());
			resultMap.put(CommonContans.STRUTS_DATA,
					topicInfoService.insert(topicInfo));
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	/**
	 * 
	 * 方法描述：根据topicInfo主机修改新闻等信息
	 * 
	 * @Title: updatetopicInfo
	 * @param @param topicInfo
	 * @param @return
	 * @return ModelMap
	 * @topicInfo topicInfoministrator 2015年1月21日
	 * @throws
	 */
	@RequestMapping(value = "/updateTopicInfo.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.updateTopicInfo", moduleName = "更新", resouceDesc = "", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap updateTopicInfo(@RequestBody TopicInfo topicInfo)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			if(null!=topicInfo&&null!=topicInfo.getTop()&&topicInfo.getTop()==0)
			{
				TopicInfo info= topicInfoService.selectMaxTop(topicInfo);
				topicInfo.setTop(info.getTop()+1);
			}else if(null!=topicInfo&&null!=topicInfo.getTop()&&topicInfo.getTop()!=0)
			{
				topicInfo.setTop(0);
			}
			resultMap.put(CommonContans.STRUTS_DATA,
					topicInfoService.updateByPrimaryKeySelective(topicInfo));
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	
	@RequestMapping(value = "/updateTopicType.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.updateTopicType", moduleName = "更新", resouceDesc = "更新帖子类型信息", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap updateTopicType(@RequestBody TopicType topicType)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			resultMap.put(CommonContans.STRUTS_DATA,
					topicTypeService.updateByPrimaryKey(topicType));
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	/**
	 * 
	 * 方法描述：根据主键删除新闻等信息
	 * 
	 * @Title: deletetopicInfo
	 * @param @param topicInfoId
	 * @param @return
	 * @return ModelMap
	 * @topicInfo topicInfoministrator 2015年1月21日
	 * @throws
	 */
	@RequestMapping(value = "/deleteTopicInfo.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.deleteTopicInfo", moduleName = "删除", resouceDesc = "", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap deleteTopicInfo(String topicInfoId)
	{
		ModelMap resultMap = new ModelMap();
		
		try
		{
			resultMap.put(CommonContans.STRUTS_DATA,
					topicInfoService.deleteByPrimaryKey(topicInfoId));
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	@RequestMapping(value = "/addTopicInfo.action", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	@ResourceAndOperate(moduleID = "com.technology.topicInfoManager.addTopicInfo", moduleName = "信息发布", resouceDesc = "信息发布,带附件的。", parentModuleID = "com.technology.topicInfoManager", parentModuleName = "新闻管理")
	public ModelMap addTopicInfo(TopicInfo topicInfo,
			@RequestParam MultipartFile[] myfiles, HttpServletRequest request)
			throws IOException
	{
		
		ModelMap resultMap = new ModelMap();
		topicInfo.setUuid(UUIDGenerateUtil.generate());
		String file = "";
		try
		{
			// 如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
			// 如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解
			// 并且上传多个文件时，前台表单中的所有<input
			// type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
			for (MultipartFile myfile : myfiles)
			{
				if (myfile.isEmpty())
				{
					System.out.println("文件未上传");
				} else
				{
					System.out.println("文件长度: " + myfile.getSize());
					System.out.println("文件类型: " + myfile.getContentType());
					System.out.println("文件名称: " + myfile.getName());
					System.out.println("文件原名: " + myfile.getOriginalFilename());
					System.out
							.println("========================================");
					// 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
					String realPath = request.getSession().getServletContext()
							.getRealPath("/image/topic");
					// 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的xIO流关掉，我是看它的源码才知道的
					String filename = System.currentTimeMillis()
							+ myfile.getOriginalFilename();
					file = "/image/topic/" + filename;
					FileUtils.copyInputStreamToFile(myfile.getInputStream(),
							new File(realPath, filename));
					topicInfo.setImgUrl(file);
				}
			}
			topicInfo.setCreateAt(new Date());
			topicInfoService.insert(topicInfo);
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
			UserInfo user = userInfoService.selectByPrimaryKey(topicInfo
					.getUserKey());
			Integer score = 0;
			if (null != user && !Tools.isEmpty(user.getScore()))
			{
				score = Integer.parseInt(user.getScore())
						+ topicInfo.getScore();
			} else
			{
				score = topicInfo.getScore();
			}
			log.info("score:" + score);
			log.info("user:" + JsonUtil.getJsonString(user));
			user.setScore(score.toString());
			userInfoService.updateByPrimaryKey(user);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
}
